package com.tech.koufu;

import com.igexin.sdk.PushManager;
import com.jeremyfeinstein.slidingmenu.lib.SlidingMenu;  
import com.tech.koufu.action.StockManager;
import com.tech.koufu.tools.PublicFuc;
import com.tech.koufu.ui.BaseSlideMenuActivity; 
import com.tech.koufu.ui.activity.ExpertsActivity;
import com.tech.koufu.ui.activity.SearchActivity;
import com.tech.koufu.ui.activity.UserDetailActivity;
import com.tech.koufu.ui.activity.login.LoginActivity;
import com.tech.koufu.ui.activity.login.RegisterActivity;
import com.tech.koufu.ui.activity.menu.MyAttentionActivity;
import com.tech.koufu.ui.activity.menu.MyCompetitions; 
import com.tech.koufu.ui.activity.menu.MyPositionsActivity;
import com.tech.koufu.ui.activity.menu.MyTrackActivity;
import com.tech.koufu.ui.activity.menu.MyTradeActivity;
import com.tech.koufu.ui.adapter.CustomViewPager;
import com.tech.koufu.ui.adapter.HomePagerAdapter; 
import com.tech.koufu.ui.view.ChooseStockFragment;
import com.tech.koufu.ui.view.CompetitionContentFragment;
import com.tech.koufu.ui.view.HomeContainerFragment; 
import com.tech.koufu.ui.view.MenuRightFragment;
import com.tech.koufu.ui.widiget.RotateFreshImageView;
import com.umeng.analytics.MobclickAgent;

import android.content.Context;
import android.content.Intent; 
import android.os.Bundle;   
import android.os.Handler;
import android.support.v4.app.FragmentTabHost; 
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.ViewPager;
import android.support.v4.app.FragmentTabHost;  
import android.util.Log; 
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener; 
import android.widget.Button;
import android.widget.ImageView; 
import android.widget.RelativeLayout; 
import android.widget.Spinner;
import android.widget.TabHost.OnTabChangeListener;
import android.widget.TabWidget;
import android.widget.TextView; 
import android.widget.Toast;

/**
 * 首页
 * @author jl_luo
 *
 */
public class MainActivity extends BaseSlideMenuActivity implements OnClickListener,OnTabChangeListener{
	private static final String TAG = MainActivity.class.getName();
	private Context mContext;
	private static final String SPEC_HOME = "home";
	private static final String SPEC_EXPERT = "expert";
	private static final String SPEC_MARKET = "market";
	private static final String SPEC_COMPETITION = "competition";
	// 抽屉菜单对象
	// private ActionBarDrawerToggle drawerbar;
//	public DrawerLayout drawerLayout;
//	private MainContentFragment contentFragment;
	private RelativeLayout left_menu_layout, right_menu_layout;
	private TextView text;
//	private ActionBar actionBar;
	
	private FragmentTabHost mTabHost;

	private Button btn_jumpsetting;
	/**
	 * head 左边头像
	 * 按钮 搜索 刷新 打开右边目录
	 */
	private ImageView icDefHead,btnSearch,btnOpenRight;
	private Spinner sp_team_type;
	public RotateFreshImageView btnRefresh;
	private TabWidget mTabWidget;
	 private long firstBackTime ;
	 private int delay_exit_time = 1500;
	 private Handler handler;
	 @Override
	public void onCreate(Bundle savedInstanceState) { 
		super.onCreate(savedInstanceState);
		PushManager.getInstance().initialize(getApplicationContext());
		mContext = this;
		initSlideMenu(); 
		initView();
		StockManager sm = new StockManager(getApplicationContext(),getApplication(),new Handler());
		sm.getNetStocks();  
//		sm.findAllLst();
		MobclickAgent.updateOnlineConfig( mContext );
	}

	 @Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		MobclickAgent.onResume(mContext);
	}
	 
	 @Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		MobclickAgent.onPause(mContext);
	}
	 
	private void initSlideMenu() {
//		getSlidingMenu().setTouchModeAbove(SlidingMenu.TOUCHMODE_FULLSCREEN); 
		//右侧菜单
		sm.setSecondaryMenu(R.layout.menu_frame_two);
//		sm.setSecondaryShadowDrawable(R.drawable.shadowright);  
//		 sm.setRightBehindWidthRes(R.dimen.right_menu_width);
//		getSupportFragmentManager()
//		.beginTransaction()
//		.replace(R.id.menu_frame_two, new MenuRightFragment())
//		.commit();
		
	}
 

	public void initView() {
		icDefHead = (ImageView)findViewById(R.id.ic_def_head);
		btnSearch = (ImageView)findViewById(R.id.btn_search);
		btnRefresh = (RotateFreshImageView)findViewById(R.id.btn_refresh);
		btnOpenRight = (ImageView)findViewById(R.id.btn_open_right);
		sp_team_type = (Spinner)findViewById(R.id.sp_team_type);	
		icDefHead.setOnClickListener(this);icDefHead.setVisibility(View.VISIBLE);
		btnSearch.setOnClickListener(this);btnSearch.setVisibility(View.VISIBLE);
//		btnRefresh.setOnClickListener(this);//btnRefresh.setVisibility(View.VISIBLE);
//		btnOpenRight.setOnClickListener(this);//btnOpenRight.setVisibility(View.VISIBLE);
		
		handler = new Handler();
//		contentFragment = new MainContentFragment();
//		FragmentManager fragmentManager = getSupportFragmentManager();
//		FragmentTransaction f_transaction = fragmentManager.beginTransaction();
//		f_transaction.replace(R.id.main_content_frame_parent, contentFragment);
//		f_transaction.commitAllowingStateLoss();
		initTabs();
//		initLeftLayout();
//		initRightLayout(); 
	}
	private RelativeLayout rl_tab_index,rl_tab_nr,rl_tab_hq,rl_tab_ss;
	private TextView txt_tab_index,txt_tab_nr,txt_tab_hq,txt_tab_ss;
	private View v_tab_index,v_tab_nr,v_tab_hq,v_tab_ss;
	private CustomViewPager vp;
	private HomePagerAdapter homePagerAdapter;
	public void initTabs(){
		vp = (CustomViewPager)findViewById(R.id.vp);
		vp.setOffscreenPageLimit(4);
		vp.setCanScroll(false);
		homePagerAdapter = new HomePagerAdapter(getSupportFragmentManager());
		vp.setAdapter(homePagerAdapter);
		rl_tab_index = (RelativeLayout)findViewById(R.id.rl_tab_index);
		rl_tab_nr = (RelativeLayout)findViewById(R.id.rl_tab_nr);
		rl_tab_hq = (RelativeLayout)findViewById(R.id.rl_tab_hq);
		rl_tab_ss = (RelativeLayout)findViewById(R.id.rl_tab_ss);
		rl_tab_index.setOnClickListener(this);
		rl_tab_nr.setOnClickListener(this);
		rl_tab_hq.setOnClickListener(this);
		rl_tab_ss.setOnClickListener(this);
		txt_tab_index = (TextView)findViewById(R.id.txt_tab_index);
		txt_tab_nr = (TextView)findViewById(R.id.txt_tab_nr);
		txt_tab_hq = (TextView)findViewById(R.id.txt_tab_hq);
		txt_tab_ss = (TextView)findViewById(R.id.txt_tab_ss);
		v_tab_index = (View)findViewById(R.id.v_tab_index);
		v_tab_nr = (View)findViewById(R.id.v_tab_nr);
		v_tab_hq = (View)findViewById(R.id.v_tab_hq);
		v_tab_ss = (View)findViewById(R.id.v_tab_ss);
		//~~~~~~~~~~~~~~~~~
		 
//		mTabHost = (FragmentTabHost)findViewById(android.R.id.tabhost);
//   	 	mTabHost.setup(this, getSupportFragmentManager(), R.id.realtabcontent); 
//   	 	//初始化4个tabs界面
//   	   //R.layout.main_bottom_bar_tab_msg  自己定义的tabs布局文件 一个Linearlayout里面放一个View组件就行了
//
////   	    View tab_index = getLayoutInflater().inflate(R.layout.main_bottom_bar_tab_index, null); 
//   	  
//   	    //addTab(标题，跳转的Fragment，传递参数的Bundle)
//   	    //ContactFragment自己定义一个extends Fragment的类就行了 
//   	    //mTabHost.getTabWidget().getChildAt(i).setBackgroundResource(R.drawable.selector_tab_background);  
//	   	 mTabHost.addTab(mTabHost.newTabSpec(SPEC_HOME).setIndicator(getIndicatorView(getResources().getString(R.string.tab_index), R.layout.tab_item)),
//	   			HomeContainerFragment.class, null);
//	     mTabHost.addTab(mTabHost.newTabSpec(SPEC_EXPERT).setIndicator(getIndicatorView(getResources().getString(R.string.tab_nr),R.layout.tab_item)),
//	    		 ExpertsContentFragment.class, null);
//	     mTabHost.addTab(mTabHost.newTabSpec(SPEC_COMPETITION).setIndicator(getIndicatorView(getResources().getString(R.string.tab_ss),R.layout.tab_item)),
//	    		 CompetitionContentFragment.class, null);
//	     mTabHost.addTab(mTabHost.newTabSpec(SPEC_MARKET).setIndicator(getIndicatorView(getResources().getString(R.string.tab_hq),R.layout.tab_item)),
//	    		 MarketContentFragment.class, null);
//	     
//   	    //设置tabs之间的分隔线不显示
//   	    mTabHost.getTabWidget().setShowDividers(LinearLayout.SHOW_DIVIDER_NONE);
//   	    mTabWidget = mTabHost.getTabWidget(); 
//   	    initTab(); 
//   	 	mTabHost.setOnTabChangedListener (this);
	}
	 
	private View getIndicatorView(String name, int layoutId) {  
        View v = getLayoutInflater().inflate(layoutId, null);  
        TextView tv = (TextView) v.findViewById(R.id.tabText);  
        tv.setText(name);  
        return v;  
    }  

	@Override
	public void onClick(View v) { 
		switch (v.getId()) {
		case R.id.ic_def_head: 
			 sm.showMenu(true);
			break;
		case R.id.btn_open_right: 
			 sm.showSecondaryMenu(true);
			break;
		case R.id.btn_search:
			Intent intent = new Intent(this,SearchActivity.class);
			startActivity(intent);
			break;
		case R.id.btn_refresh:  
			int currentItem = vp.getCurrentItem(); 
			if(currentItem==0){
				HomeContainerFragment hf = (HomeContainerFragment) homePagerAdapter.getItem(currentItem);
				showRefreshRotate();
				hf.refreshContent();
			}else if(currentItem == 3){
				CompetitionContentFragment hf = (CompetitionContentFragment) homePagerAdapter.getItem(currentItem);
				showRefreshRotate();
				hf.mainTopRefresh();
			}
			break;
		case R.id.iv_big_def_head:
			Toast.makeText(getApplicationContext(), "head pic", Toast.LENGTH_SHORT).show();
			break;
		case R.id.rl_tab_index:
			if(v_tab_index.getVisibility() != View.VISIBLE){ 
				vp.setCurrentItem(0,false);
				resetTabLine();
				showTabLine(v_tab_index);
				changeTextColor(txt_tab_index, R.color.kfColorRed);
//				btnRefresh.setVisibility(View.VISIBLE);
				sp_team_type.setVisibility(View.VISIBLE);
			}
			break;
		case R.id.rl_tab_nr:
			if(v_tab_nr.getVisibility() != View.VISIBLE){ 
				vp.setCurrentItem(1,false);
				resetTabLine();
				showTabLine(v_tab_nr);
				changeTextColor(txt_tab_nr, R.color.kfColorRed);
				btnRefresh.setVisibility(View.GONE);
			}
			break;
		case R.id.rl_tab_hq:
			if(v_tab_hq.getVisibility() != View.VISIBLE){ 
				vp.setCurrentItem(2,false);
				resetTabLine();
				showTabLine(v_tab_hq);
				changeTextColor(txt_tab_hq, R.color.kfColorRed);
//				btnRefresh.setVisibility(View.VISIBLE);
			}
			break;
		case R.id.rl_tab_ss:
			if(v_tab_ss.getVisibility() != View.VISIBLE){ 
				vp.setCurrentItem(3,false);
				resetTabLine();
				showTabLine(v_tab_ss);
				changeTextColor(txt_tab_ss, R.color.kfColorRed);
//				btnRefresh.setVisibility(View.VISIBLE);
				currentItem = vp.getCurrentItem(); 
				CompetitionContentFragment hf = (CompetitionContentFragment) homePagerAdapter.getItem(currentItem);
				hf.mainManualRefresh(0);
			}
			break;

		default:
			break;
		}
	}
	/**
	 * 修改bottom tab 样式
	 */
	private View tab1,tab2,tab3,tab4;
	private TextView tabTxt1,tabTxt2,tabTxt3,tabTxt4;
	private MyApplication myApp;
	private void initTab(){
//		mTabHost.setCurrentTab(0); 
//		mTabHost.setBackgroundColor(getResources().getColor(R.color.bgColor_6E));
//		tab1 = mTabWidget.getChildAt(0);
//		tab2 = mTabWidget.getChildAt(1);
//		tab3 = mTabWidget.getChildAt(2);
//		tab4 = mTabWidget.getChildAt(3);
//		 
////		tabTxt1 = (TextView) tab1.findViewById(android.R.id.title);
//		tabTxt2 = (TextView) tab2.findViewById(android.R.id.title);
//		tabTxt3 = (TextView) tab3.findViewById(android.R.id.title);
//		tabTxt4 = (TextView) tab4.findViewById(android.R.id.title);
////		tabTxt1.setTextColor(getResources().getColor(R.color.kfColorRed));
////		tabTxt1.setTextSize(18);
//		tabTxt2.setTextColor(getResources().getColor(R.color.textColorGray_888888));
//		tabTxt2.setTextSize(18);
//		tabTxt3.setTextColor(getResources().getColor(R.color.textColorGray_888888));
//		tabTxt3.setTextSize(18);
//		tabTxt4.setTextColor(getResources().getColor(R.color.textColorGray_888888));
//		tabTxt4.setTextSize(18);
	}

	@Override
	public void onTabChanged(String tabId) {
	
//		mTabHost.setCurrentTabByTag(tabId); 
//		int tab = mTabHost.getCurrentTab();
		Log.e(TAG, "~~~~~~~tabId="+tabId+">>+tab="); 
//		for(int i=0;i<4; i++){
//			TextView tv = (TextView) mTabWidget.getChildAt(i).findViewById(android.R.id.title);
//			if(i==tab){ 
//				tv.setTextColor(getResources().getColor(R.color.kfColorRed));
//			}else{
//				tv.setTextColor(getResources().getColor(R.color.textColorGray_888888));
//			}
//		}
		 
		
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) { 
		super.onActivityResult(requestCode, resultCode, data);
		Log.d(TAG, "onActivityResult ,mainActivity requestCode="+requestCode+">resultCode="+resultCode);
		if(requestCode== PublicFuc.CODE_Back && resultCode == PublicFuc.CODE_Back){ 
			HomeContainerFragment homeFragment = (HomeContainerFragment) homePagerAdapter.getItem(0);
			homeFragment.changeFragment();
			showLeftMenu();
		}else if(requestCode == PublicFuc.code_login_suss){
//			Toast.makeText(getApplicationContext(), "登录成灌灌灌灌灌", Toast.LENGTH_SHORT).show();
			if(data!=null){
				boolean islogin = data.getBooleanExtra("islogin", false);
				Log.w(TAG, "is Logi00n...."+islogin);
			}
			Log.w(TAG, "is Login...."+myApp.isLogin);
			if(myApp.isLogin){
				showContent();
			}
		}
	}
	public void showLeftMenu(){
		myApp = (MyApplication) getApplication();
		leftMenuFragment.showLeftMenu(myApp.isLogin);
	}
	public void showContent(){
		HomeContainerFragment homeFragment = (HomeContainerFragment) homePagerAdapter.getItem(0);
		homeFragment.changeContentFragment();
		showLeftMenu();
	}
	public void menuLoginOnclick(final View view){
		sm.showContent(true);
		handler.postDelayed(new Runnable() {

			@Override
			public void run() { 
				switch (view.getId()) {
				case R.id.rl_menu_login:
					Intent intent = new Intent(MainActivity.this,LoginActivity.class);
					 startActivityForResult(intent, PublicFuc.code_login_suss); 
					break;
				case R.id.rl_menu_register:
					 intent = new Intent(MainActivity.this,RegisterActivity.class);
					 startActivityForResult(intent, PublicFuc.code_login_suss); 
					break; 
				default:
					break;
				}
			}
			
		}, 250);
	}
	public void menuOnclick(final View view){ 
		sm.showContent(true);
		handler.postDelayed(new Runnable() {
			
			@Override
			public void run() {
				myApp = (MyApplication) getApplication();
				if(!myApp.isLogin){
//					Intent intent = new Intent(this,LoginActivity.class);   
//					startActivityForResult(intent, 3); 
					Toast.makeText(MainActivity.this, "请先登录", Toast.LENGTH_SHORT).show();
					return;
				} 
				switch (view.getId()) {
				case R.id.rl_menu_myAttention://我的关注
					Intent intent = new Intent(MainActivity.this, MyAttentionActivity.class);
					intent.putExtra("userid", myApp.getUserid());
					startActivity(intent);
					break;
				case R.id.rl_menu_myTrack://rl_menu_mytransaction
					intent = new Intent(MainActivity.this, MyTrackActivity.class); 
					startActivity(intent);
					break;
				case R.id.rl_menu_mytransaction:
					intent = new Intent(MainActivity.this, MyTradeActivity.class); 
					intent.putExtra("userid", myApp.getUserid());
					intent.putExtra("groupid", myApp.getGroupId());
					intent.putExtra("digitalid", myApp.getDigitalid());
					startActivity(intent);
					break;
				case R.id.rl_menu_my_page:
//					intent = new Intent(this, MyPageActivity.class); 
//					startActivity(intent);
					myApp = (MyApplication) getApplication();
					intent = new Intent(MainActivity.this,UserDetailActivity.class);
					intent.putExtra("userid", myApp.getUserid());
					intent.putExtra("username", myApp.getUserName());
					startActivity(intent);
					break;
				case R.id.rl_menu_my_stock_position:
					intent = new Intent(MainActivity.this, MyPositionsActivity.class); 
					startActivity(intent);
					break; 
				case R.id.rl_menu_myCompetition:
					intent = new Intent(MainActivity.this, MyCompetitions.class); 
					startActivity(intent);
					break;
				case R.id.menu_kfCompetition://right_menu
					sm.showContent(true);
					rl_tab_ss.performClick();
					break;
				case R.id.menu_stockQuotes:
					sm.showContent(true);
					rl_tab_hq.performClick();
					break;
				case R.id.menu_topranking:
					sm.showContent(true);
					rl_tab_nr.performClick();
					break;
				case R.id.menu_selfStock: 
				
						intent = new Intent(MainActivity.this,ChooseStockFragment.class); 
						intent.putExtra("userStock", myApp.mUserStocks);
						startActivity(intent); 
					break; 
				default:
					break;
				} 
			}
		}, 250);
		
		
	}
	
	private void resetTabLine(){ 
		v_tab_index.setVisibility(View.INVISIBLE);
		v_tab_nr.setVisibility(View.INVISIBLE);
		v_tab_hq.setVisibility(View.INVISIBLE);
		v_tab_ss.setVisibility(View.INVISIBLE);
		
		txt_tab_index.setTextColor(getResources().getColor(R.color.textColorGray_888888));
		txt_tab_nr.setTextColor(getResources().getColor(R.color.textColorGray_888888));
		txt_tab_hq.setTextColor(getResources().getColor(R.color.textColorGray_888888));
		txt_tab_ss.setTextColor(getResources().getColor(R.color.textColorGray_888888));
	}
	private void showTabLine(View v){
		v.setVisibility(View.VISIBLE);
	}
	private void changeTextColor(TextView tv,int colors){
		tv.setTextColor(getResources().getColor(colors));
	}
	private void showRefreshRotate(){
		btnRefresh.startRotate(R.drawable.image_progress);
	}
	public void cancleRefreshRotate(){
		btnRefresh.cancelRotete(R.drawable.btn_refresh);
	}
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) { 
		if(keyCode == KeyEvent.KEYCODE_BACK){ 
			long secondTime = System.currentTimeMillis(); 
            if (secondTime - firstBackTime > delay_exit_time) {//如果两次按键时间间隔大于800毫秒，则不退出 
                Toast.makeText(MainActivity.this, R.string.app_exit_toast_msg, 
                        Toast.LENGTH_SHORT).show(); 
                firstBackTime = secondTime;//更新firstTime 
                return false; 
            } else {  
            	finish(); 
    			System.exit(0);//否则退出程序 
            }  
		} 
		return super.onKeyDown(keyCode, event);
	}
	
}
